package com.ygu.Enter2.topic2_3合并有序链表;

//合并K个有序链表 最笨的方法
public class MergeKTwoLists {
    public ListNode mergeKLists(ListNode[] lists) {
        //合并k个链表 用一种笨办法 就是将两两进行合并操作
        ListNode res = null;
        for (ListNode listNode : lists){
            res = mergeList(res,listNode);
        }
        return  res;
    }
    public ListNode mergeList(ListNode res , ListNode listNode){
        ListNode dummy = new ListNode(-1);
        ListNode p =dummy;
        ListNode p1 = res;
        ListNode p2 = listNode;

        while (p1 != null && p2 != null){
            if(p1.val > p2.val ){
                p.next  = p2;
                p2 = p2.next;
            }else {
                p.next = p1;
                p1 = p1.next;
            }
            p = p.next;
        }

        if(p1!= null){
            p.next = p1;
        }

        if(p2!= null){
            p.next =p2;
        }
        return dummy.next;
    }
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
